//
//  Manager.swift
//  E-CycleForShop
//
//  Created by enghou on 17/3/1.
//  Copyright © 2017年 xyxorigation. All rights reserved.
//

import UIKit
let timeOut = 10.0

typealias Success = (_ model : BaseModel)->Void

typealias Fail = (_ code : Int)->Void

typealias SucDic = (_ source : Dictionary<String,Any>?)->Void
class Manager: NSObject {
    static var instance : Manager = Manager.init()
    static var queue : OperationQueue = OperationQueue.init()
    class func shared()->Manager{
        return instance
    }
    
    //用户登陆
    func userLogin(param : Dictionary<String,String>,success : Success?,fail : Fail?) -> Void {
        
        var request = URLRequest.init(url: URL.init(string: ServerAddr + Login)!, cachePolicy: URLRequest.CachePolicy.useProtocolCachePolicy, timeoutInterval: 20.0)
        request.httpMethod = "POST"
        request.httpBody = loginData(param: param)
        let worker = NetWorkerOperation.create(request: request, completion: {(param) in
            if success != nil {
                DispatchQueue.main.async {
                    let loginMod = LoginModel.init(source: param)
                    success?(loginMod)
                }
            }
        }, failed:{(code) in
            if fail != nil {
                fail!(code)
            }
        })
        Manager.queue.addOperation(worker)
    }
    
    func getMonthsData(months : String,success : Success?,fail : Fail?) -> Void {
        let hall_id = String(DataCacher.shared().id())
        let param = ["months":months,"bh_id":hall_id]
        self.basePost(path: findMonthsData, param: param, success: {(source) in
            if source != nil {
                let mod = MonthRecordModel.init(source: source)
                if success != nil {
                    DispatchQueue.main.async {
                        success!(mod)
                    }
                }
            }
        }, fail: {(code) in
            if fail != nil {
                DispatchQueue.main.async {
                    fail!(-3)
                }
            }
        })
    }
    
    //获取banner信息
    func bannerInfo(success : Success?,fail : Fail?) -> Void {
        self.basePost(path: banner, param: nil, success: {(source) in
            if source != nil {
                let mod = BannerModel.init(source: source!)
                DispatchQueue.main.async {
                    success!(mod)
                }
            }
        }, fail: {(code) in
            if fail != nil{
                DispatchQueue.main.async {
                    fail!(-3)
                }
            }
        })
    }
    
    //根据id获取手机信息
    func getPhoneInfo(id : String,success : Success?,fail : Fail?) -> Void {
        guard id.characters.count > 0 else {
            return
        }
        let param = ["id":id]
        self.basePost(path: phoneInfo, param: param, success: {(source) in
            guard source != nil else{
                return
            }
            let mod = PhoneInfoModel.init(source: source)
            DispatchQueue.main.async {
                success!(mod)
            }
        }, fail: {(code) in
            DispatchQueue.main.async {
                fail?(code)
            }
        })
    }
    
    func extraAddCompeteOrder(param : Dictionary<String,String>,success : Success?,fail : Fail?) -> Void {
        self.basePost(path: addCompleteOrder, param: param, success: {(source) in
            let mod = BaseModel.init(source: source)
            DispatchQueue.main.async {
                if success != nil {
                    success!(mod)
                }
            }
        }, fail: {(code)in
            DispatchQueue.main.async {
                fail?(code)
            }
        })
    }
    
    //添加成交纪录
    func addCompletedOrder(param : Dictionary<String,String>,success : Success?,fail : Fail?) -> Void {
        self.basePost(path: addCompleteOrder, param: param, success: {(source) in
            let mod = BaseModel.init(source: source)
            DispatchQueue.main.async {
                if success != nil {
                    success!(mod)
                }
            }
        }, fail: {(code)in
            DispatchQueue.main.async {
                fail?(code)
            }
        })
    }
    
    //获取货品的信息
    func getGoodsInfo(param : Dictionary<String,String>,success : Success?,fail : Fail?) -> Void {
        self.basePost(path: getCommodityInfo, param: param, success: {(source) in
            guard source != nil else {
                return
            }
            //拿到扣款项 dispatch
            //将扣款项保存下来用于显示
            let goods = GoodsModel.init(source: source)
            if success != nil {
                DispatchQueue.main.async {
                    success!(goods)
                }
            }
        }, fail: {(code) in
            DispatchQueue.main.async {
                fail?(code)
            }
        })
    }
    
    //得出一个手机的价格区间
    func estimatePhone(param : Dictionary<String,String>,success : Success?,fail : Fail?) -> Void {
        self.basePost(path: estimatePhones, param: param, success: {(source) in
            guard source != nil else{
                return
            }
            print(source)
            let mod = BaseModel.init(source: source)
            DispatchQueue.main.async {
                if success != nil {
                    success!(mod)
                }
            }
        }, fail: {(code) in
            DispatchQueue.main.async {
                fail?(code)
            }
        })
    }
    
    //关于我们
    func findAboutUsInfo(id : String,success : Success?,fail : Fail?)->Void{
        let param = ["id":id]
        self.basePost(path: findAboutUs, param: param, success: {(source) in
            guard source != nil else{
                return
            }
            let mod = AboutUsModel.init(source: source)
            guard success == nil else{
                DispatchQueue.main.async {
                    success!(mod)
                }
                return
            }
        }, fail: {(code) in
            guard fail == nil else {
                DispatchQueue.main.async {
                    fail!(code)
                }
                return
            }
        })
    }
    
    //根据所查的数据是日，周，天来返回数据
    func getData(kind : Int,success : Success?,fail : Fail?)->Void{
        if kind == 0 {
            getCurrentDayData(success: success, fail: fail)
        } else if kind == 1{
            getCurrentWeekData(success: success, fail: fail)
        } else if kind == 2 {
            getCurrentMonthData(success: success, fail: fail)
        }
    }
    
    func searchData(from : String,to : String,success : Success?,fail : Fail?) -> Void {
        let param = ["start":to,"end":from]
        self.basePost(path: findPerMonthData, param: param, success: {(source) in
            guard source != nil else{
                return
            }
            let model = MonthRecordModel.init(source: source)
            DispatchQueue.main.async {
                success!(model)
            }
        }, fail: {(code) in
            DispatchQueue.main.async {
                fail?(code)
            }
        })
    }
    
    //获取提现纪录,默认每页有10条数据
    func getWidthDrawRecord(page : String,success : Success?,fail : Fail?)->Void{
        let hallID = DataCacher.shared().id()
        let param = ["size":"10","nowpage":page,"bh_id":String(hallID)]
        self.basePost(path: findWidthDrawRecord, param: param, success: {(source) in
            guard source != nil else{
                return
            }
            let model = MineCollectionMessageModel.init(source: source)
            DispatchQueue.main.async {
                guard success == nil else {
                    success!(model)
                    return
                }
            }
        }, fail: {(code) in
            DispatchQueue.main.async {
                fail?(code)
            }
        })
    }
    
    //添加提现纪录
    func widthDraw(param : Dictionary<String,String>,success : Success?,fail : Fail?) -> Void {
        self.basePost(path: addWidth, param: param, success: {(source) in
            guard source != nil else {
                return
            }
            let mod = BaseModel.init(source: source)
            DispatchQueue.main.async {
                if success != nil {
                    success!(mod)
                }
            }
        }, fail: {(code) in
            DispatchQueue.main.async {
                fail?(code)
            }
        })
    }
    //获取营业员列表
    func getShopperList(success : Success?,fail : Fail?) -> Void {
        let id = DataCacher.shared().id()
        let param = ["hall_id" : String(id)]
        self.basePost(path: shopperList, param: param, success: {(source) in
            guard source != nil else {
                return
            }
            let mod = ShopperModel.init(source: source)
            DispatchQueue.main.async {
                if success != nil {
                    success!(mod)
                }
            }
        }, fail: {(code) in
            DispatchQueue.main.async {
                fail?(code)
            }
        })
    }
    
    func addShopper(name : String,success : Success?,fail : Fail?) -> Void {
        let id = DataCacher.shared().id()
        let param = ["hall_id" : String(id),"name" : name]
        self.basePost(path: addShoppers, param: param, success: {(source) in
            guard source != nil else {
                return
            }
            let mod = BaseModel.init(source: source)
            DispatchQueue.main.async {
                if success != nil {
                    success!(mod)
                }
            }
        }, fail: {(error) in
            if fail != nil {
                DispatchQueue.main.async {
                    fail?(error)
                }
            }
        })
        
    }
    
    //登出接口
    func logOut(account : String,success : Success?,fail : Fail?) -> Void {
        let param = ["account" : account]
        self.basePost(path: logout, param: param, success: {(source) in
            guard source != nil else {
                return
            }
            let mod = BaseModel.init(source: source)
            DispatchQueue.main.async {
                if success != nil {
                    success!(mod)
                }
            }
        }, fail: {(error) in
            if fail != nil {
                DispatchQueue.main.async {
                    fail?(error)
                }
            }
        })
    }
    
    func deleteShopper(id : String,success : Success?,fail : Fail?) -> Void {
        let ids = DataCacher.shared().id()
        let param = ["hall_id" : String(ids),"id" : id]
        self.basePost(path: deleteShoppers, param: param, success: {(source) in
            guard source != nil else {
                return
            }
            let mod = BaseModel.init(source: source)
            DispatchQueue.main.async {
                if success != nil {
                    success!(mod)
                }
            }
        }, fail: {(error) in
            if fail != nil {
                DispatchQueue.main.async {
                    fail!(error)
                }
            }
        })
    }
    
    //获取手机的最终估价
    func getPhoneFinalPrice(param : Dictionary<String,String>,success : Success?,fail : Fail?) -> Void {
        self.basePost(path: getFinalPrice, param: param, success: {(source) in
            guard source != nil else {
                return
            }
            let mod = BaseModel.init(source: source)
            DispatchQueue.main.async {
                success!(mod)
            }
            
        }, fail: {(code) in
            DispatchQueue.main.async {
                fail?(code)
            }
        })
    }
    
    //获取当天营业数据
    private func getCurrentDayData(success : Success?,fail : Fail?) -> Void {
        let bh_id = DataCacher.shared().id()
        if bh_id != -1 {
            self.basePost(path: findDayData, param: ["bh_id":String(bh_id)], success: {(source) in
                guard source != nil else {
                    return
                }
                let mod = TurnOverModel.init(source: source)
                DispatchQueue.main.async {
                    success!(mod)
                }
            }, fail: {(code) in
                DispatchQueue.main.async {
                    fail?(code)
                }
            })
        }
    }
    
    func getBalances(success : Success?,fail : Fail?) -> Void {
        let bh_id = DataCacher.shared().id()
        if bh_id != -1 {
            self.basePost(path: getBalance, param: ["bh_id":String(bh_id)], success: {(source) in
                let login = BalanceModel.init(source: source)
                DispatchQueue.main.async {
                    success?(login)
                }
            }, fail: {(code) in
                DispatchQueue.main.async {
                    fail?(code)
                }
            })
        }
    }
    
    //获取当周营业数据
    private func getCurrentWeekData(success : Success?,fail : Fail?)->Void{
        let bh_id = DataCacher.shared().id()
        if bh_id != -1 {
            self.basePost(path: findWeekData, param: ["bh_id":String(bh_id)], success: {(source) in
                guard source != nil else {
                    return
                }
                let mod = TurnOverModel.init(source: source)
                DispatchQueue.main.async {
                    success!(mod)
                }
            }, fail: {(code) in
                DispatchQueue.main.async {
                    fail?(code)
                }
            })
        }
    }
    
    //获取当月营业数据
    private func getCurrentMonthData(success : Success?,fail : Fail?)->Void{
        let bh_id = DataCacher.shared().id()
        if bh_id != -1 {
            self.basePost(path: findMonthData, param: ["bh_id":String(bh_id)], success: {(source) in
                guard source != nil else {
                    return
                }
                let mod = TurnOverModel.init(source: source)
                DispatchQueue.main.async {
                    success!(mod)
                }
            }, fail: {(code) in
                DispatchQueue.main.async {
                    fail?(code)
                }
            })
        }
    }
    
    //上传图片
    func addCompletion(param : Dictionary<String,String>,data : Array<Data>,success : Success?,fail : Fail?) -> Void {
        self.uploadTask(path: uploadPic, param: param, data: data, success: {(dic) in
            let mod = BaseModel.init(source: dic)
            success?(mod)
        }, fail: {(code) in
            fail?(code)
        })
    }
    
    private func uploadTask(path : String,param : Dictionary<String,String>,data : Array<Data>,success : SucDic?,fail : Fail?)->Void{
        var p = param
        let token = DataCacher.shared().token()
        let account = DataCacher.shared().account()
        p["token"] = token
        p["account"] = account
        
        let price = param["final_price"]
        if price == nil {
            return
        }
        let id = param["id"]
        if id == nil {
            return
        }
        let employee = param["employee_id"]
        if employee == nil {
            return
        }
        
        let hall_id = param["business_hall_id"]
        if hall_id == nil {
            return
        }
        
        var url = ServerAddr + path + "?" + "account=" + account + "&token=" + token
        url = url + "&final_price=" + price!
        url = url + "&id=" + id! + "&employee_id=" + employee!
        url = url + "&business_hall_id=" + hall_id!
        let manager = AFHTTPSessionManager.init()
        manager.requestSerializer = AFHTTPRequestSerializer.init()
        manager.responseSerializer = AFHTTPResponseSerializer.init()
        manager.post(url, parameters: nil, constructingBodyWith: {(formData) in
            let formatter = DateFormatter.init()
            formatter.dateFormat = "yyyy-mm-dd hh:mm:ss"
            let str = formatter.string(from: Date.init())
            for i in 0 ..< data.count{
                let name = str + String(i) + ".jpg"
                formData.appendPart(withFileData: data[i], name: "picture_url", fileName: name, mimeType: "image/jpeg")
            }
        }, progress: nil, success: {(task,da) in
            if let d = da as? Data {
                do {
                    let dict = try JSONSerialization.jsonObject(with: d, options: .allowFragments) as? Dictionary<String,Any>
                    if dict != nil {
                        success?(dict)
                    }
                }catch{
                    fail?(-3)
                }
            }
        }, failure: {(task,error) in
            fail?(-3)
        })
        
    }
    
    private func basePost(path : String,param : Dictionary<String,String>?,success : SucDic?,fail : Fail?)->Void{
        
        let request = self.request(with: path, param: param,multiPart: false)
        
        guard request != nil else {
            return
        }
        let worker = NetWorkerOperation.create(request: request!, completion: {(param) in
            if success != nil {
                success!(param)
            }
        }, failed:{(code) in
            if fail != nil {
                fail!(code)
            }
        })
        Manager.queue.addOperation(worker)
    }
    
    private func request(with path : String,param : Dictionary<String,String>?,multiPart : Bool)->URLRequest?{
        let urls = ServerAddr + path
        print(urls)
        let url = URL.init(string: urls)
        var request = URLRequest.init(url: url!, cachePolicy: URLRequest.CachePolicy.useProtocolCachePolicy, timeoutInterval: timeOut)
        request.httpMethod = "POST"
        if multiPart == true {
            request.setValue("multipart/form-data", forHTTPHeaderField: "Content-Type")
        }
        request.httpBody = self.paramData(param: param)
        return request
    }
    
    private func loginData(param : Dictionary<String,String>?)->Data?{
        guard param != nil else {
            var target = ""
            let token = DataCacher.shared().token()
            let account = DataCacher.shared().account()
            if (token.characters.count > 0 && account.characters.count > 0) {
                let tok = "token=" + token + "&account=" + account
                target.append(tok)
                let data = target.data(using: String.Encoding.utf8)
                return data
            }
            return nil
        }
        var array : Array<String> = [];
        for key in param!.keys {
            let readyToAdd = key + "=" + param![key]!
            array.append(readyToAdd)
        }
        var target = array.joined(separator: "&")
        print(target)
        let data = target.data(using: String.Encoding.utf8)
        return data
    }
    
    private func paramData(param : Dictionary<String,String>?)->Data?{
        guard param != nil else {
            var target = ""
            let token = DataCacher.shared().token()
            let account = DataCacher.shared().account()
            if (token.characters.count > 0 && account.characters.count > 0) {
                let tok = "token=" + token + "&account=" + account
                target.append(tok)
                let data = target.data(using: String.Encoding.utf8)
                return data
            }
            return nil
        }
        var array : Array<String> = [];
        for key in param!.keys {
            let readyToAdd = key + "=" + param![key]!
            array.append(readyToAdd)
        }
        var target = array.joined(separator: "&")
        let token = DataCacher.shared().token()
        let account = DataCacher.shared().account()
        if (token.characters.count > 0 && account.characters.count > 0) {
            let tok = "&token=" + token + "&account=" + account
            target.append(tok)
        }
        print(target)
        let data = target.data(using: String.Encoding.utf8)
        return data
    }
}
